import Mock from 'mockjs'

// 生成模拟数据
const table = Mock.mock({
  'list|30': [
    {
      'id|+1': 1,
      name: '@cname',
      'department|1': [
        '技术部',
        '销售部',
        '市场部',
        '人事部',
        '财务部',
        '研发部',
        '运营部',
        '客服部'
      ],
      age: '@integer(20, 50)',
      'select|1-2': 2,
      'selectSearch|1-2': 2,
      'tree|1-2': 2,
      date: '@date',
      image: Mock.Random.image('200x200', '#4A7BF7', 'Avatar')
    }
  ]
}).list

const list = Mock.mock({
  'list|2': [
    {
      'id|+1': 1,
      name: '@cname',
      age: '@integer(20, 50)',
      'select|1-2': 2,
      'selectSearch|1-2': 2,
      'tree|1-2': 2,
      date: '@date',
      image: Mock.Random.image('200x200', '#4A7BF7', 'Avatar')
    }
  ]
}).list

const mock = [
  // 分页查询接口
  {
    url: '/api/user/page',
    method: 'get',
    timeout: 500, // 模拟延迟
    response: ({ query }) => {
      // 解析查询参数
      const {
        current = 1,
        size = 10,
        name,
        age,
        select,
        selectSearch,
        tree,
        date
      } = query

      let data = [...table]

      // 过滤逻辑
      if (name)
        data = data.filter((item) => item.name.includes(name.toString()))
      if (age) data = data.filter((item) => item.age === parseInt(age))
      if (select) data = data.filter((item) => item.select === parseInt(select))
      if (selectSearch)
        data = data.filter(
          (item) => item.selectSearch === parseInt(selectSearch)
        )
      if (tree) data = data.filter((item) => item.tree === parseInt(tree))
      if (date) data = data.filter((item) => item.date === date)

      // 分页处理
      const pageSize = parseInt(size)
      const pageNum = parseInt(current)
      const start = (pageNum - 1) * pageSize
      const end = start + pageSize

      return {
        code: 200,
        data: data.slice(start, end),
        total: data.length,
        current: pageNum,
        size: pageSize
      }
    }
  },
  // list
  {
    url: '/api/user/list',
    method: 'get',
    response: ({ query }) => {
      let data = [...list]
      return {
        code: 200,
        data
      }
    }
  },
  // delete
  {
    url: '/api/user/delete',
    method: 'post',
    response: ({ query }) => {
      const { id } = query
      // 删除 table 中对应 id 的项
      const index = table.findIndex((item) => item.id === parseInt(id))
      if (index !== -1) {
        table.splice(index, 1) // 删除指定项
      }
      return {
        code: 200,
        data: null
      }
    }
  }
]

export default mock
